package googleJam.file;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileManager {

	private IFileManagerListener _fileManagerListener;
	private static FileManager s_sharedManager;
	
	public void execute ()
	{
		assert(_fileManagerListener != null);
		FileInputStream fstream;
		DataInputStream in = null;
		try {
			fstream = new FileInputStream(_fileManagerListener.getInputNameFilePath());
			in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			int index = 0;
			while ((strLine = br.readLine()) != null)   {
			  _fileManagerListener.onReadingLine(strLine,index);
			  index ++ ;
			}
			_fileManagerListener.onFinishingExecute();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void writeFile (String content,String filePath)
	{
		FileWriter fstream;
		BufferedWriter out = null;
		try {
			fstream = new FileWriter(filePath);
			out = new BufferedWriter(fstream);
			out.write(content);
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null)
			{
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
		   
	
	public static FileManager getSharedManager()
	{
		if (s_sharedManager == null) {
			s_sharedManager = new FileManager();
		}
		return s_sharedManager;
	}
	
	public void setFileManagerListener(IFileManagerListener fileManagerListener)
	{
		_fileManagerListener = fileManagerListener;
	}
}
